//
//  ST_PinterestNewGirlsViewController.swift
//  btvideo
//
//  Created by mac on 2020/4/14.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import HandyJSON
import SwifterSwift
import SwiftyJSON
/**
 新人  弃用
 */
class ST_PinterestNewGirlsViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = Color.white
//        self.left_nav_btn.isHidden = true
        self.right_nav_btn.isHidden = false
        self.title_nav_btn.setTitleForAllStates("今日加入的新人")
        
        
        view.addSubview(unlike_btn)
        view.addSubview(like_btn)
        
        let offSet = 10
        
        unlike_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(80)
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-49-16)
            make.right.equalTo(view.snp.centerX).offset(-offSet)
        }
        
        like_btn.snp.makeConstraints { (make) in
            make.bottom.width.height.equalTo(unlike_btn)
            make.left.equalTo(view.snp.centerX).offset(offSet)
        }
        
        
        view.addSubview(koloda_view)
        koloda_view.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalTo(unlike_btn.snp.top).offset(-10)
            make.top.equalTo(own_navigation_bar.snp.bottom).offset(15)
        }
        
        view.addSubview(emptyView)
        emptyView.snp.makeConstraints { (make) in
            make.centerX.width.equalToSuperview()
            make.height.equalTo(emptyView.figured_height)
            make.centerY.equalToSuperview().offset( iPhoneXSeries ? -70 : -80)
        }
        
        koloda_view.backgroundCardsTopMargin = 0
        
        koloda_view.delegate = self
        koloda_view.dataSource = self
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.refresh_pairs_love_controller, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.ban_somebody, object: nil)
        
        request_data()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func refresh_data(){
        
        self.currentPage = 0
        self.request_data()
    }
    
    @objc func clear_data(){
        currentPage = 0
        self.data_array.removeAll()
        self.koloda_view.reloadData()
    }
    
    override func right_click() {
        
        self.navigationController?.pushViewController(ST_IgnoreLoveViewController())
        
    }
    
//    MARK: - View  DataSet
    fileprivate var currentPage = 0
    
//    /**
//     当前本地未读数
//     */
//    fileprivate var unread_like_number = 0
    
    fileprivate var lastPlayView:ST_PairsLoveItemView?
    
    fileprivate var currentView:ST_PairsLoveItemView?{
        get{
            
            if let item = koloda_view.viewForCard(at: koloda_view.currentCardIndex) as? ST_PairsLoveItemView{
                return item
            }
            return nil
        }
    }
    
    open var api = PH.fetchNewGirlsApi
    
    fileprivate var currentPageCount = 0
    
    fileprivate var data_array = [ST_PairsLoveItemViewModel]()
    fileprivate func request_data(){
        
        currentPage += 1
        
        let param = ["page":currentPage,
                    "size":20] as [String : Any]
        
        
        JVrequest(api,parameters:param, success: { (json) in
            
            let data = json["data"]
            
            print("今日加入的新人数据：",data)
            
            var array = [ST_PairsLoveItemViewModel]()
            
            for item in data.arrayValue{
                
                if let model = ST_PairsLoveItemViewModel.deserialize(from: item.dictionaryObject){
                    
                    let albumList = ST_PairsShareParticularModel.describe(json_array: item["album"].arrayValue)
                    
                    model.album = albumList
                    
                    array.append(model)
                }
            }
            
            if self.currentPage == 1{
                self.data_array = array
            }else{
                self.data_array += array
            }
            
            self.currentPageCount = array.count
            
            self.previous_direction_array.removeAll()
            self.koloda_view.resetCurrentCardIndex()
             
            self.emptyView.isHidden = self.data_array.count > 0
            self.koloda_view.isHidden = self.data_array.count < 1
            self.like_btn.isHidden = self.koloda_view.isHidden
            self.unlike_btn.isHidden = self.koloda_view.isHidden
            

            
            
            
        }) { (code, err) in
            
            self.koloda_view.resetCurrentCardIndex()
            self.emptyView.isHidden = self.data_array.count > 0
            self.koloda_view.isHidden = self.data_array.count < 1
            self.like_btn.isHidden = self.koloda_view.isHidden
            self.unlike_btn.isHidden = self.koloda_view.isHidden
            
            ToastHud(text: err, view: self.view)
        }
    }
    

//    MARK: - Properties
    var previous_direction_array = [SwipeResultDirection]()
    
    
    fileprivate lazy var koloda_view: KolodaView = {
        let control = KolodaView()
        return control
    }()
    
    
    
    lazy var emptyView:ST_ActiveEmptyView = {
        let control = ST_ActiveEmptyView.init(title: "啊哦~等会儿让新人就来啦！", imageName: ST_ImageUtils.imageName("新人空视图")!)
        control.imageSize = CGSize.init(width: 120, height: 120)
        control.isHidden = true
        return control
    }()
    
    
    fileprivate lazy var unlike_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_icon_不喜欢")!)
        control.add_touch_up(insideTarget: self, action: #selector(unlike_handle))
        control.isHidden = true
        return control
    }()
    
    fileprivate lazy var like_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_icon_喜欢")!)
        control.add_touch_up(insideTarget: self, action: #selector(like_handle))
        control.isHidden = true
        return control
    }()
}

//MARK:- Event
extension ST_PinterestNewGirlsViewController{
    
    @objc func unlike_handle(){
        
        koloda_view.swipe(SwipeResultDirection.left)
        
    }
    @objc func like_handle(){
        
        koloda_view.swipe(SwipeResultDirection.right)
        
    }
}

//MARK:- Notification observer
extension ST_PinterestNewGirlsViewController{
    
    @objc func register_finish_handle(){
        
        currentPage = 0
        
        request_data()
        
    }
    
}
//MARK:- KolodaView Delegate
extension ST_PinterestNewGirlsViewController:KolodaViewDelegate,KolodaViewDataSource{
    
    
    func kolodaDidRunOutOfCards(_ koloda: KolodaView) {
        
        if self.currentPageCount < 20{
            return
        }
        
        currentPage += 1
        
        self.data_array.removeAll()
        
        request_data()
        
    }
    
    func koloda(_ koloda: KolodaView, didSwipeCardAt index: Int, in direction: SwipeResultDirection) {
        
        
        self.previous_direction_array.append(direction)

        guard let currentModel = self.data_array[safe:index] ,let photo = currentModel.album.first  else {
            lastPlayView?.stop()
            return
        }
        
        let info_model = ST_MatchUserInfo.init(accid: currentModel.accid, avatar: photo.imageUrl, nickname: currentModel.nickname)
            
//       喜欢接口调用
        if direction == .right || direction == .topRight || direction == .bottomRight {
            
            likeBehavior(info: info_model, isLike: true, loveSquare: false,refreshloveIndex:false, loveWay: ST_LoveWay.recommend, peculiarity: "" , responseClosure: { (f) in
                
                print("滑过Index:",index)
                //                最后一个
                if self.data_array.count == index + 1{
                    self.emptyView.isHidden = false
                    self.koloda_view.isHidden = true
                    self.like_btn.isHidden = self.koloda_view.isHidden
                    self.unlike_btn.isHidden = self.koloda_view.isHidden
                }
                
            }) {
             
                if let direction = self.previous_direction_array.last{
                
                    self.previous_direction_array.removeLast()
                    main_thread_execute(afterDelay: 1) {
                        self.koloda_view.revert_action(direction: direction)
                    }
                }
            }
            
            
        }
//       不喜欢接口调用
        else{
//             likeBehavior(info: info_model, isLike: false, loveSquare: true)
            
            likeBehavior(info: info_model, isLike: false, loveSquare: false,refreshloveIndex:false, loveWay: ST_LoveWay.recommend, peculiarity: "", responseClosure: { (f) in
                
                print("滑过Index:",index)
                //                最后一个
                if self.data_array.count == index + 1{
                    self.emptyView.isHidden = false
                    self.koloda_view.isHidden = true
                    self.like_btn.isHidden = self.koloda_view.isHidden
                    self.unlike_btn.isHidden = self.koloda_view.isHidden
                }
                
            }) {
             
                if let direction = self.previous_direction_array.last{
                
                    self.previous_direction_array.removeLast()
                    main_thread_execute(afterDelay: 1) {
                        self.koloda_view.revert_action(direction: direction)
                    }
                }
            }
            
        }
        
    }
    
    func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
        
        let itemView = ST_PairsLoveItemView()
        if let model = data_array[safe:index]{
            itemView.bind_view_data_set(model: model)
        }
        
        itemView.love_square_operation = false
        
        return itemView
    }
    
    func koloda(_ koloda: KolodaView, didSelectCardAt index: Int) {
        
        guard let model = data_array[safe:index] else{
            return
        }
        
        
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = model.accid
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
    }
    
    
    
    func kolodaNumberOfCards(_ koloda: KolodaView) -> Int {
        return data_array.count
    }
    
    func koloda(_ koloda: KolodaView, didShowCardAt index: Int) {
    
        lastPlayView?.stop()
    
        self.currentView?.play()
        
    }
    
    func koloda(_ koloda: KolodaView, viewForCardOverlayAt index: Int) -> KolodaOverlayView? {
        return ST_SampleOverLayView()
        
    }
}




//MARK: - 活跃用户查看
//
class PinterestActiveViweController: ST_PinterestNewGirlsViewController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title_nav_btn.setTitleForAllStates("现在活跃的人")
    }
    
    override var api: String{
        get{
            return PH.fetchActiveGirlsApi
        }set{
            super.api = newValue
        }
    }
    
    private lazy var _emptyView: ST_ActiveEmptyView = {
        let control = ST_ActiveEmptyView.init(title: "等等~活跃用户马上就到！", imageName: ST_ImageUtils.imageName("首页_img_活跃(空)")!)
        control.imageSize = CGSize.init(width: 120, height: 120)
        control.isHidden = true
        return control
    }()

    override var emptyView: ST_ActiveEmptyView {
      get { return _emptyView }
      set { _emptyView = newValue }
    }
    
}
